package com.client.task;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;

import com.client.bean.User;
import com.client.common.ValueStack;
import com.client.db.DataService;
import com.client.net.Request;
import com.clinet.cache.Log;

public class LoginlTask extends AsyncTask<User, Void, Integer> {
	public interface Callback {

		void onComplete(Integer result);
	}

	private final Context context;
	private Callback callback;

	private DataService mDataService=null;
	private String path = ValueStack.ROOT+"/forestry/user_login.action";
	private Request mRequest = null;

	public LoginlTask(Context context, Callback callback) {
		this.context = context;
		this.callback = callback;
		mRequest = new Request(path);
		if(mDataService==null)
		{
			mDataService=new DataService(context);
		}
	}

	// 用户登录：
	// http://localhost:8013/forestry/user_login.action?username=admin&password=123456
	// 正确返回：
	// {"success":true,"userId":"28856C5085D84C3E926FB74A42823FCA","sessionId":"3AE6BC94F1A10C8EC13F706AE849265C"}
	// 错误返回：
	// {"success":false,"message":"用户名或密码错误！"}
	/**
	 * The task should be executed with one given source photo uri.
	 */
	@Override
	protected Integer doInBackground(User... params) {
		int code = 0;
		if (params[0] == null) {
			code = 0;
		} else {
			if (!iscancle) {
				Map<String, String> ps = new HashMap<String, String>();
				ps.put("username", params[0].userName);
				ps.put("password", params[0].password);
				try {
					String temp = mRequest.postFormData(ps);
					Log.i("postText" + temp);
					JSONObject obj = new JSONObject(temp);
					boolean falg = obj.getBoolean("success");
					if (falg) {
						params[0].userId = obj.getString("userId");
						params[0].sessionid = obj.getString("sessionId");
						params[0].current = "true";
						mDataService.updateUser(params[0]);
						ValueStack.getInstance().setValue("USER", params[0]);
						// params[0].userId = "111111";
						code = 1;
					} else {
						code = 0;
					}
				} catch (Exception e) {
				}

			}
		}
		return code;
	}

	@Override
	protected void onPostExecute(Integer result) {
		if (!iscancle && callback != null) {
			callback.onComplete(result);
		}
	}

	private boolean iscancle = false;

	public void release() {
		callback = null;
		try {
			mRequest.cancle();
		} catch (IOException e) {
		}
	}
}
